<template>
  <div class="progress-tracking">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon><TrendCharts /></el-icon>
          进度跟踪
        </h1>
        <div class="header-actions">
          <el-button @click="exportProgress">
            <el-icon><Download /></el-icon>
            导出进度
          </el-button>
          <el-button type="primary" @click="updateProgress">
            <el-icon><Refresh /></el-icon>
            更新进度
          </el-button>
        </div>
      </div>
    </div>

    <!-- 进度概览卡片 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon overall">
                <el-icon><PieChart /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">总体进度</div>
                <div class="card-value">{{ progressOverview.overallProgress }}%</div>
                <div class="card-desc">按计划进行</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon tasks">
                <el-icon><List /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">任务总数</div>
                <div class="card-value">{{ progressOverview.totalTasks }}</div>
                <div class="card-desc">已完成: {{ progressOverview.completedTasks }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon milestone">
                <el-icon><Flag /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">里程碑</div>
                <div class="card-value">{{ progressOverview.completedMilestones }}/{{ progressOverview.totalMilestones }}</div>
                <div class="card-desc">下个: {{ progressOverview.nextMilestone }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon delay">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">延期任务</div>
                <div class="card-value">{{ progressOverview.delayedTasks }}</div>
                <div class="card-desc">需要关注</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 功能标签页 -->
    <el-card class="main-content">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 任务进度 -->
        <el-tab-pane label="任务进度" name="tasks">
          <div class="tasks-container">
            <div class="tasks-toolbar">
              <el-button type="primary" @click="addTask">
                <el-icon><Plus /></el-icon>
                新增任务
              </el-button>
              <el-button @click="batchUpdateProgress">
                <el-icon><Edit /></el-icon>
                批量更新
              </el-button>
              <div class="toolbar-right">
                <el-select v-model="taskStatusFilter" placeholder="任务状态" style="width: 150px">
                  <el-option label="全部" value="" />
                  <el-option label="未开始" value="not-started" />
                  <el-option label="进行中" value="in-progress" />
                  <el-option label="已完成" value="completed" />
                  <el-option label="已延期" value="delayed" />
                </el-select>
                <el-select v-model="taskPriorityFilter" placeholder="优先级" style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="高" value="high" />
                  <el-option label="中" value="medium" />
                  <el-option label="低" value="low" />
                </el-select>
                <el-input
                  v-model="taskSearchText"
                  placeholder="搜索任务"
                  style="width: 200px"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
            </div>
            
            <el-table :data="filteredTaskData" border style="width: 100%" row-key="id">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="任务名称" width="200" show-overflow-tooltip />
              <el-table-column prop="assignee" label="负责人" width="100">
                <template #default="{ row }">
                  <div class="assignee-info">
                    <el-avatar :size="24" :src="row.assigneeAvatar" />
                    <span>{{ row.assignee }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="80">
                <template #default="{ row }">
                  <el-tag :type="getPriorityType(row.priority)" size="small">
                    {{ getPriorityText(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)" size="small">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="progress" label="进度" width="150">
                <template #default="{ row }">
                  <div class="progress-cell">
                    <el-progress
                      :percentage="row.progress"
                      :color="getProgressColor(row.progress, row.status)"
                      :stroke-width="8"
                    />
                    <span class="progress-text">{{ row.progress }}%</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="startDate" label="开始日期" width="120" />
              <el-table-column prop="endDate" label="结束日期" width="120" />
              <el-table-column prop="duration" label="工期(天)" width="80" />
              <el-table-column label="延期天数" width="80">
                <template #default="{ row }">
                  <span :class="getDelayClass(row.delayDays)">
                    {{ row.delayDays > 0 ? `+${row.delayDays}` : row.delayDays }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="updateTaskProgress(row)">
                    更新进度
                  </el-button>
                  <el-button type="success" size="small" @click="viewTaskDetail(row)">
                    详情
                  </el-button>
                  <el-button size="small" @click="editTask(row)">
                    编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 甘特图 -->
        <el-tab-pane label="甘特图" name="gantt">
          <div class="gantt-container">
            <div class="gantt-toolbar">
              <el-radio-group v-model="ganttTimeScale" @change="updateGanttChart">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
              <div class="toolbar-right">
                <el-button @click="zoomIn">
                  <el-icon><ZoomIn /></el-icon>
                  放大
                </el-button>
                <el-button @click="zoomOut">
                  <el-icon><ZoomOut /></el-icon>
                  缩小
                </el-button>
                <el-button @click="resetZoom">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
                <el-button type="primary" @click="showCriticalPath">
                  <el-icon><Connection /></el-icon>
                  关键路径
                </el-button>
              </div>
            </div>
            
            <!-- 甘特图表 -->
            <div ref="ganttChart" class="gantt-chart" style="height: 600px;"></div>
          </div>
        </el-tab-pane>

        <!-- 里程碑管理 -->
        <el-tab-pane label="里程碑" name="milestones">
          <div class="milestones-container">
            <div class="milestones-toolbar">
              <el-button type="primary" @click="addMilestone">
                <el-icon><Plus /></el-icon>
                新增里程碑
              </el-button>
              <el-button @click="generateMilestoneReport">
                <el-icon><Document /></el-icon>
                生成报告
              </el-button>
            </div>
            
            <!-- 里程碑时间线 -->
            <div class="milestone-timeline">
              <el-timeline>
                <el-timeline-item
                  v-for="milestone in milestoneData"
                  :key="milestone.id"
                  :timestamp="milestone.date"
                  :type="getMilestoneType(milestone.status)"
                  :icon="getMilestoneIcon(milestone.status)"
                  placement="top"
                >
                  <el-card class="milestone-card">
                    <div class="milestone-header">
                      <h4>{{ milestone.name }}</h4>
                      <el-tag :type="getMilestoneStatusType(milestone.status)" size="small">
                        {{ milestone.status }}
                      </el-tag>
                    </div>
                    <p class="milestone-desc">{{ milestone.description }}</p>
                    <div class="milestone-info">
                      <div class="info-item">
                        <span class="label">负责人:</span>
                        <span class="value">{{ milestone.responsible }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">完成度:</span>
                        <span class="value">{{ milestone.completionRate }}%</span>
                      </div>
                      <div class="info-item">
                        <span class="label">关联任务:</span>
                        <span class="value">{{ milestone.relatedTasks }}个</span>
                      </div>
                    </div>
                    <div class="milestone-actions">
                      <el-button type="primary" size="small" @click="updateMilestone(milestone)">
                        更新状态
                      </el-button>
                      <el-button size="small" @click="viewMilestoneDetail(milestone)">
                        查看详情
                      </el-button>
                      <el-button size="small" @click="editMilestone(milestone)">
                        编辑
                      </el-button>
                    </div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>
        </el-tab-pane>

        <!-- 关键路径分析 -->
        <el-tab-pane label="关键路径" name="critical-path">
          <div class="critical-path-container">
            <div class="critical-path-toolbar">
              <el-button type="primary" @click="calculateCriticalPath">
                <el-icon><DataAnalysis /></el-icon>
                计算关键路径
              </el-button>
              <el-button @click="optimizePath">
                <el-icon><Setting /></el-icon>
                路径优化
              </el-button>
            </div>
            
            <!-- 关键路径图表 -->
            <div class="path-analysis">
              <el-row :gutter="20">
                <el-col :span="16">
                  <el-card>
                    <template #header>
                      <span>关键路径网络图</span>
                    </template>
                    <div ref="criticalPathChart" style="height: 500px;"></div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card>
                    <template #header>
                      <span>路径分析</span>
                    </template>
                    <div class="path-info">
                      <div class="info-section">
                        <h4>关键路径</h4>
                        <div class="critical-tasks">
                          <el-tag
                            v-for="task in criticalPathTasks"
                            :key="task.id"
                            type="danger"
                            style="margin: 2px;"
                          >
                            {{ task.name }}
                          </el-tag>
                        </div>
                      </div>
                      
                      <div class="info-section">
                        <h4>路径统计</h4>
                        <div class="stats">
                          <div class="stat-item">
                            <span class="label">总工期:</span>
                            <span class="value">{{ pathStats.totalDuration }}天</span>
                          </div>
                          <div class="stat-item">
                            <span class="label">关键任务:</span>
                            <span class="value">{{ pathStats.criticalTasks }}个</span>
                          </div>
                          <div class="stat-item">
                            <span class="label">浮动时间:</span>
                            <span class="value">{{ pathStats.floatTime }}天</span>
                          </div>
                          <div class="stat-item">
                            <span class="label">风险等级:</span>
                            <el-tag :type="getRiskType(pathStats.riskLevel)" size="small">
                              {{ pathStats.riskLevel }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                      
                      <div class="info-section">
                        <h4>优化建议</h4>
                        <ul class="suggestions">
                          <li v-for="suggestion in optimizationSuggestions" :key="suggestion">
                            {{ suggestion }}
                          </li>
                        </ul>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane>

        <!-- 进度报表 -->
        <el-tab-pane label="进度报表" name="reports">
          <div class="reports-container">
            <div class="reports-toolbar">
              <el-date-picker
                v-model="reportDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 250px"
              />
              <el-button type="primary" @click="generateProgressReport">
                <el-icon><Document /></el-icon>
                生成报表
              </el-button>
              <el-button @click="exportReport">
                <el-icon><Download /></el-icon>
                导出报表
              </el-button>
            </div>
            
            <!-- 报表图表 -->
            <div class="report-charts">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>进度趋势图</span>
                    </template>
                    <div ref="progressTrendChart" style="height: 300px;"></div>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>任务完成情况</span>
                    </template>
                    <div ref="taskCompletionChart" style="height: 300px;"></div>
                  </el-card>
                </el-col>
              </el-row>
              
              <el-row :gutter="20" style="margin-top: 20px;">
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>人员工作量分布</span>
                    </template>
                    <div ref="workloadDistributionChart" style="height: 300px;"></div>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card>
                    <template #header>
                      <span>延期风险分析</span>
                    </template>
                    <div ref="delayRiskChart" style="height: 300px;"></div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 任务进度更新对话框 -->
    <el-dialog v-model="showProgressDialog" title="更新任务进度" width="500px">
      <el-form :model="currentTaskProgress" ref="progressForm" label-width="100px">
        <el-form-item label="任务名称">
          <el-input v-model="selectedTask.name" disabled />
        </el-form-item>
        <el-form-item label="当前进度" prop="progress">
          <el-slider
            v-model="currentTaskProgress.progress"
            :min="0"
            :max="100"
            :step="5"
            show-stops
            show-input
          >
            <template #default="{ value }">
              {{ value }}%
            </template>
          </el-slider>
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-select v-model="currentTaskProgress.status" style="width: 100%">
            <el-option label="未开始" value="not-started" />
            <el-option label="进行中" value="in-progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已延期" value="delayed" />
          </el-select>
        </el-form-item>
        <el-form-item label="实际开始" prop="actualStartDate">
          <el-date-picker
            v-model="currentTaskProgress.actualStartDate"
            type="date"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预计完成" prop="estimatedEndDate">
          <el-date-picker
            v-model="currentTaskProgress.estimatedEndDate"
            type="date"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="进度说明">
          <el-input
            v-model="currentTaskProgress.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入进度更新说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showProgressDialog = false">取消</el-button>
        <el-button type="primary" @click="saveTaskProgress">确定</el-button>
      </template>
    </el-dialog>

    <!-- 里程碑编辑对话框 -->
    <el-dialog v-model="showMilestoneDialog" title="里程碑管理" width="600px">
      <el-form :model="currentMilestone" ref="milestoneForm" label-width="100px">
        <el-form-item label="里程碑名称" prop="name">
          <el-input v-model="currentMilestone.name" placeholder="请输入里程碑名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="currentMilestone.description"
            type="textarea"
            :rows="2"
            placeholder="请输入里程碑描述"
          />
        </el-form-item>
        <el-form-item label="计划日期" prop="date">
          <el-date-picker
            v-model="currentMilestone.date"
            type="date"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="responsible">
          <el-select v-model="currentMilestone.responsible" style="width: 100%">
            <el-option
              v-for="person in availablePersonnel"
              :key="person.id"
              :label="person.name"
              :value="person.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联任务">
          <el-select
            v-model="currentMilestone.relatedTaskIds"
            multiple
            style="width: 100%"
            placeholder="选择关联任务"
          >
            <el-option
              v-for="task in taskData"
              :key="task.id"
              :label="task.name"
              :value="task.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showMilestoneDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMilestone">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import {
  TrendCharts,
  Download,
  Refresh,
  PieChart,
  List,
  Flag,
  Warning,
  Plus,
  Edit,
  Search,
  ZoomIn,
  ZoomOut,
  Connection,
  Document,
  DataAnalysis,
  Setting
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const router = useRouter()

// 响应式数据
const activeTab = ref('tasks')
const taskStatusFilter = ref('')
const taskPriorityFilter = ref('')
const taskSearchText = ref('')
const ganttTimeScale = ref('week')
const reportDateRange = ref([])
const showProgressDialog = ref(false)
const showMilestoneDialog = ref(false)

// 图表引用
const ganttChart = ref(null)
const criticalPathChart = ref(null)
const progressTrendChart = ref(null)
const taskCompletionChart = ref(null)
const workloadDistributionChart = ref(null)
const delayRiskChart = ref(null)

// 表单引用
const progressForm = ref(null)
const milestoneForm = ref(null)

// 进度概览数据
const progressOverview = reactive({
  overallProgress: 68,
  totalTasks: 45,
  completedTasks: 28,
  totalMilestones: 8,
  completedMilestones: 5,
  nextMilestone: '系统测试',
  delayedTasks: 3
})

// 任务数据
const taskData = ref([
  {
    id: 1,
    name: '需求分析',
    assignee: '张三',
    assigneeAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    priority: 'high',
    status: 'completed',
    progress: 100,
    startDate: '2024-01-01',
    endDate: '2024-01-15',
    duration: 15,
    delayDays: 0
  },
  {
    id: 2,
    name: '系统设计',
    assignee: '李四',
    assigneeAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    priority: 'high',
    status: 'in-progress',
    progress: 75,
    startDate: '2024-01-16',
    endDate: '2024-02-05',
    duration: 20,
    delayDays: 2
  },
  {
    id: 3,
    name: '前端开发',
    assignee: '王五',
    assigneeAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    priority: 'medium',
    status: 'not-started',
    progress: 0,
    startDate: '2024-02-06',
    endDate: '2024-03-15',
    duration: 38,
    delayDays: 0
  },
  {
    id: 4,
    name: '后端开发',
    assignee: '赵六',
    assigneeAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    priority: 'medium',
    status: 'delayed',
    progress: 30,
    startDate: '2024-02-01',
    endDate: '2024-03-10',
    duration: 38,
    delayDays: 5
  }
])

// 里程碑数据
const milestoneData = ref([
  {
    id: 1,
    name: '项目启动',
    description: '项目正式启动，团队组建完成',
    date: '2024-01-01',
    status: '已完成',
    responsible: '张三',
    completionRate: 100,
    relatedTasks: 3
  },
  {
    id: 2,
    name: '需求确认',
    description: '需求分析完成，客户确认',
    date: '2024-01-15',
    status: '已完成',
    responsible: '李四',
    completionRate: 100,
    relatedTasks: 5
  },
  {
    id: 3,
    name: '设计评审',
    description: '系统设计方案评审通过',
    date: '2024-02-05',
    status: '进行中',
    responsible: '王五',
    completionRate: 75,
    relatedTasks: 4
  },
  {
    id: 4,
    name: '开发完成',
    description: '前后端开发全部完成',
    date: '2024-03-15',
    status: '未开始',
    responsible: '赵六',
    completionRate: 0,
    relatedTasks: 8
  }
])

// 关键路径数据
const criticalPathTasks = ref([
  { id: 1, name: '需求分析' },
  { id: 2, name: '系统设计' },
  { id: 4, name: '后端开发' },
  { id: 6, name: '系统测试' }
])

const pathStats = reactive({
  totalDuration: 120,
  criticalTasks: 4,
  floatTime: 5,
  riskLevel: '中等'
})

const optimizationSuggestions = ref([
  '增加后端开发人员以缩短关键路径',
  '并行执行前端和后端开发任务',
  '提前准备测试环境和测试用例',
  '加强团队沟通，减少等待时间'
])

// 可用人员列表
const availablePersonnel = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' },
  { id: 4, name: '赵六' }
])

// 当前编辑的数据
const selectedTask = reactive({})
const currentTaskProgress = reactive({
  progress: 0,
  status: '',
  actualStartDate: '',
  estimatedEndDate: '',
  notes: ''
})

const currentMilestone = reactive({
  id: null,
  name: '',
  description: '',
  date: '',
  responsible: '',
  relatedTaskIds: []
})

// 计算属性
const filteredTaskData = computed(() => {
  let filtered = taskData.value
  
  if (taskStatusFilter.value) {
    filtered = filtered.filter(task => task.status === taskStatusFilter.value)
  }
  
  if (taskPriorityFilter.value) {
    filtered = filtered.filter(task => task.priority === taskPriorityFilter.value)
  }
  
  if (taskSearchText.value) {
    filtered = filtered.filter(task => 
      task.name.toLowerCase().includes(taskSearchText.value.toLowerCase())
    )
  }
  
  return filtered
})

// 方法
const getPriorityType = (priority) => {
  const typeMap = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'success'
  }
  return typeMap[priority] || 'info'
}

const getPriorityText = (priority) => {
  const textMap = {
    'high': '高',
    'medium': '中',
    'low': '低'
  }
  return textMap[priority] || priority
}

const getStatusType = (status) => {
  const typeMap = {
    'not-started': 'info',
    'in-progress': 'warning',
    'completed': 'success',
    'delayed': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'not-started': '未开始',
    'in-progress': '进行中',
    'completed': '已完成',
    'delayed': '已延期'
  }
  return textMap[status] || status
}

const getProgressColor = (progress, status) => {
  if (status === 'delayed') return '#F56C6C'
  if (progress >= 80) return '#67C23A'
  if (progress >= 50) return '#E6A23C'
  return '#409EFF'
}

const getDelayClass = (delayDays) => {
  if (delayDays > 0) return 'text-danger'
  if (delayDays < 0) return 'text-success'
  return 'text-info'
}

const getMilestoneType = (status) => {
  const typeMap = {
    '已完成': 'success',
    '进行中': 'warning',
    '未开始': 'info'
  }
  return typeMap[status] || 'info'
}

const getMilestoneIcon = (status) => {
  const iconMap = {
    '已完成': 'SuccessFilled',
    '进行中': 'Loading',
    '未开始': 'Clock'
  }
  return iconMap[status] || 'Clock'
}

const getMilestoneStatusType = (status) => {
  const typeMap = {
    '已完成': 'success',
    '进行中': 'warning',
    '未开始': 'info'
  }
  return typeMap[status] || 'info'
}

const getRiskType = (riskLevel) => {
  const typeMap = {
    '低': 'success',
    '中等': 'warning',
    '高': 'danger'
  }
  return typeMap[riskLevel] || 'info'
}

const addTask = () => {
  ElMessage.info('新增任务功能开发中...')
}

const batchUpdateProgress = () => {
  ElMessage.info('批量更新功能开发中...')
}

const updateTaskProgress = (task) => {
  Object.assign(selectedTask, task)
  Object.assign(currentTaskProgress, {
    progress: task.progress,
    status: task.status,
    actualStartDate: task.startDate,
    estimatedEndDate: task.endDate,
    notes: ''
  })
  showProgressDialog.value = true
}

const viewTaskDetail = (task) => {
  ElMessage.info(`查看任务 "${task.name}" 的详细信息`)
}

const editTask = (task) => {
  ElMessage.info(`编辑任务 "${task.name}"`)
}

const saveTaskProgress = async () => {
  try {
    // 这里应该调用API保存任务进度
    const taskIndex = taskData.value.findIndex(t => t.id === selectedTask.id)
    if (taskIndex > -1) {
      Object.assign(taskData.value[taskIndex], {
        progress: currentTaskProgress.progress,
        status: currentTaskProgress.status
      })
    }
    
    ElMessage.success('任务进度更新成功')
    showProgressDialog.value = false
    
    // 重新初始化图表
    nextTick(() => {
      initReportCharts()
      updateGanttChart()
    })
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const addMilestone = () => {
  Object.assign(currentMilestone, {
    id: null,
    name: '',
    description: '',
    date: '',
    responsible: '',
    relatedTaskIds: []
  })
  showMilestoneDialog.value = true
}

const updateMilestone = (milestone) => {
  ElMessage.info(`更新里程碑 "${milestone.name}" 状态`)
}

const viewMilestoneDetail = (milestone) => {
  ElMessage.info(`查看里程碑 "${milestone.name}" 详情`)
}

const editMilestone = (milestone) => {
  Object.assign(currentMilestone, { ...milestone })
  showMilestoneDialog.value = true
}

const saveMilestone = async () => {
  try {
    if (currentMilestone.id) {
      // 编辑里程碑
      const index = milestoneData.value.findIndex(m => m.id === currentMilestone.id)
      if (index > -1) {
        Object.assign(milestoneData.value[index], { ...currentMilestone })
      }
      ElMessage.success('里程碑更新成功')
    } else {
      // 新增里程碑
      const newMilestone = {
        ...currentMilestone,
        id: Date.now(),
        status: '未开始',
        completionRate: 0,
        relatedTasks: currentMilestone.relatedTaskIds.length
      }
      milestoneData.value.push(newMilestone)
      ElMessage.success('里程碑添加成功')
    }
    
    showMilestoneDialog.value = false
  } catch (error) {
    console.error('保存里程碑失败:', error)
  }
}

const generateMilestoneReport = () => {
  ElMessage.info('生成里程碑报告功能开发中...')
}

const calculateCriticalPath = () => {
  ElMessage.success('关键路径计算完成')
  nextTick(() => {
    initCriticalPathChart()
  })
}

const optimizePath = () => {
  ElMessage.info('路径优化功能开发中...')
}

const updateGanttChart = () => {
  nextTick(() => {
    initGanttChart()
  })
}

const zoomIn = () => {
  ElMessage.info('甘特图放大功能开发中...')
}

const zoomOut = () => {
  ElMessage.info('甘特图缩小功能开发中...')
}

const resetZoom = () => {
  ElMessage.info('甘特图重置功能开发中...')
}

const showCriticalPath = () => {
  ElMessage.info('显示关键路径功能开发中...')
}

const generateProgressReport = () => {
  ElMessage.info('生成进度报表功能开发中...')
}

const exportReport = () => {
  ElMessage.info('导出报表功能开发中...')
}

const exportProgress = () => {
  ElMessage.info('导出进度功能开发中...')
}

const updateProgress = () => {
  ElMessage.info('更新进度功能开发中...')
}

// 初始化甘特图
const initGanttChart = () => {
  if (!ganttChart.value) return
  
  const chart = echarts.init(ganttChart.value)
  
  // 模拟甘特图数据
  const ganttData = taskData.value.map((task, index) => ({
    name: task.name,
    value: [
      index,
      new Date(task.startDate).getTime(),
      new Date(task.endDate).getTime(),
      task.progress
    ],
    itemStyle: {
      color: getProgressColor(task.progress, task.status)
    }
  }))
  
  const option = {
    title: {
      text: '项目甘特图',
      left: 'center'
    },
    tooltip: {
      formatter: function(params) {
        const start = new Date(params.value[1]).toLocaleDateString()
        const end = new Date(params.value[2]).toLocaleDateString()
        return `${params.name}<br/>开始: ${start}<br/>结束: ${end}<br/>进度: ${params.value[3]}%`
      }
    },
    grid: {
      left: '10%',
      right: '10%',
      top: '15%',
      bottom: '15%'
    },
    xAxis: {
      type: 'time',
      position: 'top',
      splitLine: {
        lineStyle: {
          color: ['#E9EDFF']
        }
      },
      axisLine: {
        show: false
      }
    },
    yAxis: {
      type: 'category',
      data: taskData.value.map(task => task.name),
      inverse: true,
      axisTick: {
        show: false
      },
      axisLine: {
        show: false
      }
    },
    series: [
      {
        type: 'custom',
        renderItem: function(params, api) {
          const categoryIndex = api.value(0)
          const start = api.coord([api.value(1), categoryIndex])
          const end = api.coord([api.value(2), categoryIndex])
          const height = api.size([0, 1])[1] * 0.6
          
          return {
            type: 'rect',
            shape: {
              x: start[0],
              y: start[1] - height / 2,
              width: end[0] - start[0],
              height: height
            },
            style: api.style()
          }
        },
        data: ganttData
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化关键路径图表
const initCriticalPathChart = () => {
  if (!criticalPathChart.value) return
  
  const chart = echarts.init(criticalPathChart.value)
  
  // 模拟关键路径网络图数据
  const nodes = [
    { id: '1', name: '需求分析', x: 100, y: 100 },
    { id: '2', name: '系统设计', x: 300, y: 100 },
    { id: '3', name: '前端开发', x: 500, y: 50 },
    { id: '4', name: '后端开发', x: 500, y: 150 },
    { id: '5', name: '系统测试', x: 700, y: 100 },
    { id: '6', name: '项目交付', x: 900, y: 100 }
  ]
  
  const links = [
    { source: '1', target: '2' },
    { source: '2', target: '3' },
    { source: '2', target: '4' },
    { source: '3', target: '5' },
    { source: '4', target: '5' },
    { source: '5', target: '6' }
  ]
  
  const option = {
    title: {
      text: '关键路径网络图',
      left: 'center'
    },
    series: [
      {
        type: 'graph',
        layout: 'none',
        symbolSize: 60,
        roam: true,
        label: {
          show: true,
          position: 'inside',
          fontSize: 10
        },
        edgeSymbol: ['circle', 'arrow'],
        edgeSymbolSize: [4, 10],
        data: nodes.map(node => ({
          ...node,
          itemStyle: {
            color: criticalPathTasks.value.some(task => task.name === node.name) ? '#F56C6C' : '#409EFF'
          }
        })),
        links: links,
        lineStyle: {
          opacity: 0.9,
          width: 2,
          curveness: 0
        }
      }
    ]
  }
  
  chart.setOption(option)
}

// 初始化报表图表
const initReportCharts = () => {
  // 进度趋势图
  if (progressTrendChart.value) {
    const trendChart = echarts.init(progressTrendChart.value)
    
    const trendOption = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value',
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [
        {
          name: '计划进度',
          type: 'line',
          data: [10, 25, 45, 65, 80, 100],
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '实际进度',
          type: 'line',
          data: [8, 22, 40, 58, 68, 75],
          itemStyle: {
            color: '#67C23A'
          }
        }
      ]
    }
    
    trendChart.setOption(trendOption)
  }
  
  // 任务完成情况
  if (taskCompletionChart.value) {
    const completionChart = echarts.init(taskCompletionChart.value)
    
    const completionOption = {
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          name: '任务状态',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 28, name: '已完成', itemStyle: { color: '#67C23A' } },
            { value: 12, name: '进行中', itemStyle: { color: '#E6A23C' } },
            { value: 3, name: '已延期', itemStyle: { color: '#F56C6C' } },
            { value: 2, name: '未开始', itemStyle: { color: '#909399' } }
          ]
        }
      ]
    }
    
    completionChart.setOption(completionOption)
  }
  
  // 人员工作量分布
  if (workloadDistributionChart.value) {
    const workloadChart = echarts.init(workloadDistributionChart.value)
    
    const workloadOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: ['张三', '李四', '王五', '赵六']
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [
        {
          name: '工作负荷',
          type: 'bar',
          data: [85, 75, 60, 90],
          itemStyle: {
            color: function(params) {
              const colors = ['#67C23A', '#E6A23C', '#F56C6C']
              if (params.value >= 80) return colors[2]
              if (params.value >= 70) return colors[1]
              return colors[0]
            }
          }
        }
      ]
    }
    
    workloadChart.setOption(workloadOption)
  }
  
  // 延期风险分析
  if (delayRiskChart.value) {
    const riskChart = echarts.init(delayRiskChart.value)
    
    const riskOption = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['第1周', '第2周', '第3周', '第4周', '第5周', '第6周']
      },
      yAxis: {
        type: 'value',
        name: '风险指数'
      },
      series: [
        {
          name: '延期风险',
          type: 'line',
          data: [2, 3, 4, 6, 5, 3],
          itemStyle: {
            color: '#F56C6C'
          },
          areaStyle: {
            color: 'rgba(245, 108, 108, 0.3)'
          }
        }
      ]
    }
    
    riskChart.setOption(riskOption)
  }
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initGanttChart()
    initCriticalPathChart()
    initReportCharts()
  })
})
</script>

<style scoped>
.progress-tracking {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.overview-card:hover {
  transform: translateY(-2px);
}

.card-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.card-icon.overall {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.tasks {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.milestone {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.delay {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-desc {
  font-size: 12px;
  color: #909399;
}

.main-content {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tasks-container,
.gantt-container,
.milestones-container,
.critical-path-container,
.reports-container {
  padding: 20px;
}

.tasks-toolbar,
.gantt-toolbar,
.milestones-toolbar,
.critical-path-toolbar,
.reports-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.assignee-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-text {
  font-size: 12px;
  color: #606266;
  min-width: 35px;
}

.gantt-chart {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
}

.milestone-timeline {
  max-height: 600px;
  overflow-y: auto;
}

.milestone-card {
  margin-bottom: 16px;
}

.milestone-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.milestone-header h4 {
  margin: 0;
  color: #303133;
}

.milestone-desc {
  color: #606266;
  margin-bottom: 12px;
}

.milestone-info {
  display: flex;
  gap: 20px;
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  gap: 4px;
}

.info-item .label {
  color: #909399;
  font-size: 12px;
}

.info-item .value {
  color: #303133;
  font-size: 12px;
  font-weight: 500;
}

.milestone-actions {
  display: flex;
  gap: 8px;
}

.path-analysis {
  margin-top: 20px;
}

.path-info {
  padding: 16px;
}

.info-section {
  margin-bottom: 20px;
}

.info-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
}

.critical-tasks {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-item .label {
  color: #909399;
  font-size: 12px;
}

.stat-item .value {
  color: #303133;
  font-size: 12px;
  font-weight: 500;
}

.suggestions {
  margin: 0;
  padding-left: 16px;
}

.suggestions li {
  color: #606266;
  font-size: 12px;
  margin-bottom: 4px;
}

.report-charts {
  margin-top: 20px;
}

.text-danger {
  color: #F56C6C;
}

.text-success {
  color: #67C23A;
}

.text-info {
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .progress-tracking {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .tasks-toolbar,
  .gantt-toolbar,
  .milestones-toolbar,
  .critical-path-toolbar,
  .reports-toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .toolbar-right {
    justify-content: center;
    margin-top: 12px;
  }
  
  .milestone-info {
    flex-direction: column;
    gap: 8px;
  }
  
  .milestone-actions {
    justify-content: center;
  }
  
  .gantt-chart {
    height: 400px !important;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 20px;
  }
  
  .card-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .card-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .card-value {
    font-size: 20px;
  }
  
  .gantt-chart {
    height: 300px !important;
  }
  
  .path-analysis .el-col {
    margin-bottom: 20px;
  }
}
</style>